package services

import (
	"encoding/json"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"my-go-gateway/dao"
	"my-go-gateway/dto"
	"my-go-gateway/middleware"
	"my-go-gateway/public"
)

type AdminService struct {
}

func (adminService *AdminService) ChangePwd(ctx *gin.Context, params *dto.ChangePwdInput) (error, middleware.ResponseCode) {
	//1. session读取用户信息到结构体 sessInfo
	//2. sessInfo.ID 读取数据库信息 adminInfo
	//3. params.password+adminInfo.salt sha256 saltPassword
	//4. saltPassword==> adminInfo.password 执行数据保存
	session := sessions.Default(ctx)
	adminSessionInfo := session.Get(public.AdminSessionInfoKey)
	sessionInfo := &dto.AdminSessionInfo{}
	err := json.Unmarshal([]byte(fmt.Sprint(adminSessionInfo)), sessionInfo)
	if err != nil {
		return err, 2000
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		return err, 2001
	}
	adminInfo := &dao.Admin{}
	adminInfo, err = adminInfo.Find(ctx, tx, &dao.Admin{UserName: sessionInfo.UserName})
	if err != nil {
		return err, 2002
	}
	newPassword := public.GenSaltPassword(adminInfo.Salt, params.Password)
	adminInfo.Password = newPassword
	if err = adminInfo.Save(ctx, tx); err != nil {
		return nil, 2003
	}
	return nil, 200
}
